<?php
class PDF
{
	public $filename;
	public $pdf_renderer;
	public $objects;
	public $template;

	const TEMPLATE_CONTRACT = 'Contract';

	public function __construct($objects, $template, $smarty)
	{
		$this->pdf_renderer = new PDFGenerator(false);
		$this->template = $template;
		$this->smarty = $smarty;

		$this->objects = $objects;
		if (!($objects instanceof Iterator) && !is_array($objects))
			$this->objects = array($objects);
	}

	public function render($display = true)
	{
		$render = false;
		$this->pdf_renderer->setFontForLang("fr");
		//foreach ($this->objects as $object)
		//{
			$template = $this->getTemplateObject($this->objects);
			if (!$template)
				continue;

			if (empty($this->filename))
			{
				$this->filename = $template->getFilename();
				if (count($this->objects) > 1)
					$this->filename = $template->getBulkFilename();
			}

			
			$this->pdf_renderer->createHeader($template->getHeader());
			$this->pdf_renderer->createFooter($template->getFooter());
			$this->pdf_renderer->createContent($template->getContent());
			
		
			$this->pdf_renderer->writePage();
			$render = true;

			unset($template);
		//}

		if ($render)
		{
			// clean the output buffer
			if (ob_get_level() && ob_get_length() > 0)
				ob_clean();
			return $this->pdf_renderer->render($this->filename, $display);
		}
	}

	public function getTemplateObject($object)
	{
		$class = false;
		$classname = 'HTMLTemplate'.$this->template;

		if (class_exists($classname))
		{
			$class = new $classname($object, $this->smarty);
			if (!($class instanceof HTMLTemplate))
				throw new Exception('Invalid class. It should be an instance of HTMLTemplate');
		}

		return $class;
	}
}